<!-- 角色编辑弹窗 -->
<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <div class="flex-between">
          <span class="hLabel">{{ isUpdate ? '消费详情' : '领取优惠券' }}</span>
          <el-button class="fixed"
                     :loading="loading"
                     @click="allReceiveCoupons()"
                     type="danger"
                     style="margin-right: 30px;">
            全部领取
          </el-button>
          <!-- <span @click="allReceiveCoupons(item)" style="color: #fff;height: 30px;width: 80px;background-color: red;text-align: center;line-height: 30px;margin-right:10px" >全部领取</span> -->
        </div>
      </template>
      <div>
        <div v-infinite-scroll="loadCoupon"
             style="overflow-y: auto; height: 90vh">
          <!-- <div v-for="(item,index) in packageOrderLists"
             class="infinite-list-item"
             :key="index">{{ index }}</div> -->
          <div v-for="(item, index) in couponLists"
               :key="index">
            <div class="content">
              <div class="positionCoupon flex">
                <span class="font-overflow">{{ item.name }}</span>
              </div>
              <div class="couponPrice">
                <div class="flex-between">
                  <div class="flex">
                    <div style="min-width: 70px"
                         class="left">
                      <span style="color: rgb(255, 0, 0)">￥</span>
                      <span style="
                          color: rgb(255, 0, 0);
                          font-family: Inter;
                          font-size: 32px;
                        ">{{ totelName(item.discount_intensity) }}</span>
                    </div>
                    <div class="flex-columns"
                         style="height: 77px; justify-content: space-between">
                      <span style="color: rgb(255, 0, 0); font-size: 18px">{{
                        item.type === 3
                          ? '无门槛福利优惠券'
                          : '满' +
                            totelName(item.trigger_amount) +
                            '减' +
                            totelName(item.discount_intensity) +
                            '元'
                      }}</span>
                      <span style="color: rgb(255, 0, 0); font-size: 18px">{{
                        item.desc
                      }}</span>
                      <span style="color: rgb(153, 153, 153); font-size: 12px">{{ extractedDate(item.end_time) }}到期
                      </span>
                    </div>
                  </div>
                  <div class="claimNow flex"
                       @click="receiveCoupons(item)">
                    立即领取
                  </div>
                </div>
              </div>
            </div>
          </div>
          <p v-if="couponloading">加载中...</p>
          <p class="flex margin_20px_0"
             v-if="noMoreCoupon && couponLists.length">没有更多优惠券了</p>
          <ele-empty v-if="noMoreCoupon && !couponLists.length"
                     class="flex-column"
                     style="height: 100px"
                     text="哎呀, 还没有优惠券~" />
        </div>
      </div>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>

<script>
import { couponList, receiveCoupon } from '@/api/order/cashierRecharge';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';


export default {
  name: 'pictureEdit',
  components: { ElImageViewer },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {
    const categoryImage = (rule, value, callback) => {
      console.log(this.form.img);
      if (!this.form.img) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const DEFAULT_FORM = {
      // 分类名称
      name: '',
      //   分类图片
      img: '',
      // 排序号
      sort: ''
    };
    return {
      loading: false,
      storageMode: '',
      consumptionDetails: '',
      options: [],
      imageUrl: '',
      imgViewArr: [],
      pageCoupon: 1,
      viewerVisible: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,
      // 表单验证规则
      rules: {
        name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }
        ],

        sort: [
          {
            required: true,
            message: '请输入排序值',
            trigger: 'blur'
          }
        ],
        // 站点 图片上传
        categoryImages: [
          { required: true, validator: categoryImage, trigger: 'change' }
        ]
      },

      // 是否是修改
      isUpdate: false,
      showChoose: false,
      couponLists: [],
      couponCount: [],
      couponloading: false,
      selectCouponIndex: 100
    };
  },
  activated () {
    // operate_type
  },
  computed: {
    // 是否开启响应式布局
    styleResponsive () {
      return this.$store.state.theme.styleResponsive;
    },
    finalPrice: function () {
      return function (price, couponPrice) {
        let result;
        console.log(price, couponPrice);
        result = (Math.floor(price * Number(this.discount)) / 100).toFixed(2);

        // result = (price * this.discount) / 100
        if (this.goodsInfo.buying_pattern == 1) {
          result = result - couponPrice - this.deduction_integral_ratio;
        } else {
          result = result - couponPrice;
        }
        // result = result - couponPrice;
        this.form.amount = Math.max(0, result.toFixed(2));
        this.$emit('showSettlement', true);
        this.$emit('totlelPrice', {
          // 支付价格
          finalPrice: Math.max(0, result.toFixed(2)),
          //优惠券价格
          couponPrice: couponPrice,
          //  抵扣价格
          deduction_integral_ratio: this.deduction_integral_ratio,
          //   原价
          originalPrice: this.goodsInfo.price * Number(this.goodsform.number),
          // 数量
          number: this.goodsform.number,
          // 商品id
          goods_id: this.goodsInfo.id,
          // 用户id
          uid: this.userInfo.id,
          //   是否进行积分抵扣
          points_offset: this.goodsform.points_offset,
          //   积分
          surplus_integral: this.userInfo.surplus_integral,
          pay_way: 1,
          coupon_id: this.goodsform.coupon_id,
          balance: this.userInfo.balance
        });
        return Math.max(0, result.toFixed(2)); // 防止出行负数
      };
    },
    extractedDate: function () {
      return function (time) {
        return time.split(' ')[0];
      };
    },
    totelName: function () {
      return function (nums) {
        let num;
        if (nums.endsWith('.00')) {
          num = nums.slice(0, -3); // 去除末尾的 ".00"
        }
        if (nums >= 10000) {
          let remainder = num % 10000;
          let quotient = Math.floor(num / 10000);
          let decimal = Math.floor(remainder / 1000);
          return quotient + '.' + decimal + '万';
        } else {
          return num ? num : nums;
        }
      };
    }
  },
  methods: {
    noMoreCoupon () {
      return this.couponLists.length >= this.couponCount;
    },
    async allReceiveCoupons () {
      this.loading = true
      const idArr = this.couponLists.map((item) => {
        return item.id
      })

      const res = await receiveCoupon({
        id: idArr,
        uid: this.data
        // classify_id: this.goodsInfo.classify_id,
        // uid: this.userInfo.id
      });

      if (res.code == 0) {
        this.loading = false
        this.$message.success(res.msg)
        this.pageCoupon = 1
        this.couponLists = []
        this.couponListFn()
      } else {
        this.loading = false
        this.$message.error(res.msg)
      }
    },
    async receiveCoupons (item,) {
      const res = await receiveCoupon({
        id: [item.id],
        uid: this.data
        // classify_id: this.goodsInfo.classify_id,
        // uid: this.userInfo.id
      });

      if (res.code == 0) {
        this.$message.success(res.msg)
        this.pageCoupon = 1
        this.couponLists = []
        this.couponListFn()

      } else {
        this.$message.error(res.msg)
      }
    },
    async couponListFn () {
      this.couponloading = true;
      const res = await couponList({
        page: this.pageCoupon,
        limit: 10,
        uid: this.data
        // classify_id: this.goodsInfo.classify_id,
        // uid: this.userInfo.id
      });

      if (res.code == 0) {
        this.couponloading = false;
        //   this.packageOrderLists = res.data.list
        this.couponCount = res.data.count;

        if (this.couponCount == this.couponLists.length) {
          this.disabledCoupon = true;
        } else {
          this.couponLists = [...this.couponLists, ...res.data.list];
          console.log(this.couponLists);
          this.pageCoupon += 1;
          this.disabledCoupon = false;
        }
      } else {
        this.couponloading = false;
        console.log(res);
      }
    },
    loadCoupon () {
      console.log('11111');
      if (this.couponCount != this.couponLists.length) {
        this.couponListFn();
      } else {
        this.disabledCoupon = true;
      }
    },
    // 获取存储配置
    // async storageConfig () {
    //   const res = await storageConfigDetail();

    //   // console.log(res.storageMode);

    //   this.storageMode = res?.storageMode;
    // },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove () {
      this.fileList = [];
      this.imageUrl = '';
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
      this.$emit('Refresh', true);
    },
    async handleFileChange (file, fileList) {
      console.log(this.storageMode);
      if (this.storageMode == 2) {
        this.aliFn(file, fileList);
      } else if (this.storageMode == 3) {
        this.qnyFn(file, fileList);
      }
    },

    // 点击按钮预览图片
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    }

    /* 更新visible */
  },

  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(async () => {
        if (visible) {
          console.log(visible);
          this.couponListFn();
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.content {
  width: 95%;
  border-radius: 10px;
  margin: 15px;
  margin-bottom: 10px;
  background: rgb(255, 242, 242);

  .positionCoupon {
    padding: 4px;
    width: 72px;
    height: 25px;
    border-radius: 10px 0px 10px 0px;
    color: rgb(255, 0, 0);
    background: rgb(255, 219, 219);
    font-size: 12px;
  }

  .couponPrice {
    padding: 10px 13px;

    .left {
      margin-right: 16px;
    }

    .claimNow {
      width: 77px;
      height: 29px;
      border-radius: 17px;
      color: #fff;
      background: rgb(255, 0, 0);
    }
  }
}
.packageCardArr {
  position: relative;
  margin-top: 32px;
  padding: 25px 20px;
  height: 108px;
  border-radius: 20px;
  background-repeat: no-repeat;
  background-size: cover;

  background-image: (var(--bg-image));
  // background-image: url('../../../static/套餐卡背景/矩形 1591.png');

  .avatar {
    width: 40px;
    height: 40px;
    margin-right: 20px;
  }

  .rechargeBtn {
    width: 61.25px;
    height: 26px;
    border-radius: 20px;
    z-index: 999;
    background: rgb(255, 255, 255);
  }

  .rechargeBtn-noListing {
    width: 110px;
    height: 52px;
    border-radius: 10px;
  }

  .centerText {
    width: 258px;
  }

  .price {
    color: #fff;
    font-size: 16px;
    font-weight: 700;
  }

  .priceText {
    color: rgb(255, 255, 255);
    font-size: 16px;
    font-weight: 400;
  }
}
.realNameStyle {
  position: relative;
  .avaterName {
    width: 90px;
    height: 90px;
    margin-right: 10px;
    vertical-align: middle;
    margin-right: 5px;
  }
  .addClocks {
    position: absolute;
    top: 0;
    width: 30px;
    line-height: 24px;
    text-align: center;
    height: 24px;
    background-color: #1890ff;
  }
  .technicianName {
    color: #1890ff;
    font-size: 12px;
    font-style: normal;
    font-weight: 400;
  }
}
.orderPageDescribe {
  // padding-right: 90px;

  .img {
    width: 100px;
    height: 100px;
  }
}
/*隐藏input（type=number)右边的小箭头*/
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.height83 {
  height: 43vh;
}
.hLabel {
  margin: 10px 0 0px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
